"""
文件上传接口
"""
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from app.schemas.common import ApiResponse
from app.services.minio_service import minio_service
from app.core.dependencies import get_current_user, get_current_user_for_upload
from app.models.user import User
from loguru import logger
from typing import List

router = APIRouter()


@router.post("/image", response_model=ApiResponse[str])
async def upload_image(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """
    上传图片
    支持格式: JPG, JPEG, PNG, GIF
    """
    # 检查文件类型
    allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
    if file.content_type not in allowed_types:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型: {file.content_type}。仅支持 JPG, PNG, GIF"
        )
    
    # 检查文件大小 (5MB)
    file_content = await file.read()
    file_size = len(file_content)
    max_size = 5 * 1024 * 1024  # 5MB
    
    if file_size > max_size:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大: {file_size / 1024 / 1024:.2f}MB。最大支持 5MB"
        )
    
    if not minio_service:
        raise HTTPException(
            status_code=503,
            detail="文件上传服务不可用"
        )
    
    try:
        # 重置文件指针
        await file.seek(0)
        
        # 上传到 MinIO
        file_url = minio_service.upload_file(
            file_obj=file.file,
            file_name=file.filename or "image.jpg",
            content_type=file.content_type or "image/jpeg",
            folder="images"
        )
        
        logger.info(f"用户 {current_user.id} 上传图片: {file_url}")
        
        return ApiResponse(
            code=0,
            message="上传成功",
            data=file_url
        )
    except Exception as e:
        logger.error(f"上传图片失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"上传失败: {str(e)}"
        )


@router.post("/avatar", response_model=ApiResponse[str])
async def upload_avatar(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user_for_upload)
):
    """
    上传头像
    支持格式: JPG, JPEG, PNG
    支持通过URL参数传递token（兼容微信小程序uploadFile）
    例如: POST /upload/avatar?token=xxx
    """
    # 检查文件类型
    allowed_types = ['image/jpeg', 'image/jpg', 'image/png']
    if file.content_type not in allowed_types:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型: {file.content_type}。仅支持 JPG, PNG"
        )
    
    # 检查文件大小 (2MB)
    file_content = await file.read()
    file_size = len(file_content)
    max_size = 2 * 1024 * 1024  # 2MB
    
    if file_size > max_size:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大: {file_size / 1024 / 1024:.2f}MB。最大支持 2MB"
        )
    
    if not minio_service:
        raise HTTPException(
            status_code=503,
            detail="文件上传服务不可用"
        )
    
    try:
        # 重置文件指针
        await file.seek(0)
        
        # 上传到 MinIO
        file_url = minio_service.upload_file(
            file_obj=file.file,
            file_name=file.filename or "avatar.jpg",
            content_type=file.content_type or "image/jpeg",
            folder="avatars"
        )
        
        logger.info(f"用户 {current_user.id} 上传头像: {file_url}")
        
        return ApiResponse(
            code=0,
            message="上传成功",
            data=file_url
        )
    except Exception as e:
        logger.error(f"上传头像失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"上传失败: {str(e)}"
        )


@router.post("/team-logo", response_model=ApiResponse[str])
async def upload_team_logo(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user_for_upload)
):
    """
    上传球队 Logo
    支持格式: JPG, JPEG, PNG
    支持通过URL参数传递token（兼容微信小程序uploadFile）
    例如: POST /upload/team-logo?token=xxx
    """
    # 检查文件类型
    allowed_types = ['image/jpeg', 'image/jpg', 'image/png']
    if file.content_type not in allowed_types:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型: {file.content_type}。仅支持 JPG, PNG"
        )
    
    # 检查文件大小 (2MB)
    file_content = await file.read()
    file_size = len(file_content)
    max_size = 2 * 1024 * 1024  # 2MB
    
    if file_size > max_size:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大: {file_size / 1024 / 1024:.2f}MB。最大支持 2MB"
        )
    
    if not minio_service:
        raise HTTPException(
            status_code=503,
            detail="文件上传服务不可用"
        )
    
    try:
        # 重置文件指针
        await file.seek(0)
        
        # 上传到 MinIO
        file_url = minio_service.upload_file(
            file_obj=file.file,
            file_name=file.filename or "logo.jpg",
            content_type=file.content_type or "image/jpeg",
            folder="team-logos"
        )
        
        logger.info(f"用户 {current_user.id} 上传球队 Logo: {file_url}")
        
        return ApiResponse(
            code=0,
            message="上传成功",
            data=file_url
        )
    except Exception as e:
        logger.error(f"上传球队 Logo 失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"上传失败: {str(e)}"
        )

